package cn.yangliu.config.custom;

import java.util.Objects;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * @author 杨柳
 * @date 2019-06-02
 */
@Component
public class TokenStoreImpl implements TokenStore {

    private static final String TOKENS = "tokens";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void store(String token, Authentication authentication) {
        redisTemplate.opsForValue().set(token, JSON.toJSONString(authentication));
    }

    @Override
    public Authentication getAuthentication(String token) {
        Object authentication = redisTemplate.opsForValue().get(token);
        if (Objects.isNull(authentication)){
            return null;
        }
        return JSON.parseObject(authentication.toString(), UsernamePasswordAuthenticationToken.class);
    }

    @Override
    public boolean remove(String token) {
        return redisTemplate.delete(token);
    }
}
